package com.sunflower.common.core.validation;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.sunflower.common.core.validation.constraints.IsPhoneNumber;
import com.sunflower.common.core.validation.enums.MobilePatternEnum;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * TODO
 *
 * @author: SunLuQuan
 * @Date: 2024年05月10日 09:44
 * @Description: IsPhoneNumberValidator
 */
public class IsPhoneNumberValidator implements ConstraintValidator<IsPhoneNumber, String> {

    private MobilePatternEnum mobilePatternEnum;

    @Override
    public void initialize(IsPhoneNumber annotation) {
        this.mobilePatternEnum = annotation.pattern();
    }

    /**
     * 验证是否是手机号码格式
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 忽略空字符串
        if (StrUtil.isNotEmpty(value)) {
            return Validator.isMatchRegex(mobilePatternEnum.getPattern(), value);
        }
        return true;
    }
}
